package com.hddf.project.auth.timer_task;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.kommii.common_utils.DateTime_Utils;

import com.hddf.project.auth.service.AESKeyService;
import com.hddf.project.auth.service.CookieService;

public class AutoRunServlet extends HttpServlet {

	private static final long serialVersionUID = -1476537721353939368L;
	private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
	Timer timer = null;
	Timer othertimer = null;

	public AutoRunServlet() {
		super();
		timer = new Timer();
		othertimer = new Timer();
	}

	public void destroy() {
		timer.cancel();
		super.destroy();
	}

	// 增加或减少天数
	public Date addDay(Date date, int num) {
		Calendar startDT = Calendar.getInstance();
		startDT.setTime(date);
		startDT.add(Calendar.DAY_OF_MONTH, num);
		return startDT.getTime();
	}

	public void init() throws ServletException {
		System.out.println(">>start timer task>>");
		System.out.println(">>init mongodb  pool>>");
		String str_interval_time = this.getInitParameter("interval_time");
		String str_cookie_domain = this.getInitParameter("cookie_domain");
		String str_task_time = this.getInitParameter("task_time");
		System.out.println(str_task_time);
		try {
			System.out.println(str_cookie_domain);
			Class.forName("com.kommii.mongodb_utils.Mongodb_ConnPools");
			System.out.println(str_interval_time);
			CookieService.setDomain(str_cookie_domain);
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		//执行任务的时间0-23
		int task_time = Integer.parseInt(str_task_time);
		Calendar calendar = Calendar.getInstance();
		/*** 定制每日2:00执行方法 ***/
		calendar.set(Calendar.HOUR_OF_DAY, task_time);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		Date date = calendar.getTime(); //第一次执行定时任务的时间
		//如果第一次执行定时任务的时间 小于 当前的时间
		//此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。
		if (date.before(new Date())) {
			//date = this.addDay(date, 1);
		}
		OtherTask task = new OtherTask();
		//timer.schedule(new DeleteTask(), 1000, 900000);//延时1秒执行,然后每间隔15分钟执行一次删除操作
		timer.schedule(new AesKeyDeleteTask(), 60000, Long.parseLong(str_interval_time));
		othertimer.schedule(task, date, PERIOD_DAY);
	}

}

class AesKeyDeleteTask extends TimerTask {

	@Override
	public void run() {
		try {
			AESKeyService aks = AESKeyService.getInstance();
			long current_time = DateTime_Utils.getCurrentSeconds();
			aks.deleteTimeOutAesKeys(current_time);
			Date date = new Date();
			System.out.println("++++ delete unusefull aeskeys +++++"
					+ date.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

class OtherTask extends TimerTask {

	@Override
	public void run() {
		try {
			System.out.println("++++ handle  other task +++++");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
